package report

import (
	"../common"
	"../web"
	"strconv"
	"strings"
	"time"
)

type QuerySsnObj struct {
	common.BaseHandler
}

func ProductReportPrint(ssns, conn string) (string, string) {
	printStr := ""
	urltype := ""
	pntset := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(A.SQLTEXT, ''), ISNULL(A.HTMLFILE, '')
   		   FROM SFC_PRINTVERSION A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
  		  WHERE B.SSN_NO=?
    		AND B.WONO=C.WONO 
    		AND C.ITEM=A.ITEM`,
		conn, new(common.PrintSqlAndFile), ssns)
	sqltxt := strings.TrimSpace(pntset.(common.PrintSqlAndFile).SqlText)
	switch sqltxt {
	case "getAntennaTestData":
		testdata, _, _ := GetAntennaTestData(ssns, conn)
		if testdata.ElecB || testdata.PhaseB {
			printStr = ssns
			urltype = "prtsn"
		}
	case "getPassiveTestData":
		printStr = ssns
		urltype = "prtsn"
	case "getGpsTestData":
		printStr = ssns
		urltype = "prtsn"
	}
	return printStr, urltype
}

func (self *QuerySsnObj) Prepare() {}

func (self *QuerySsnObj) ParameterCheck() bool {
	prtsn := strings.TrimSpace(self.Ctx.Params["prtsn"])
	if prtsn != "" {
		urltype := ""
		vals := *common.FetchOneRowPtr(
			`SELECT TOP 1 LTRIM(RTRIM(ISNULL(A.PRODTYPE, ''))) 
			   FROM SFC_ITEMS A(NOLOCK), SFC_WO B(NOLOCK), SFC_SSN C(NOLOCK)
			  WHERE C.SSN_NO=? 
			    AND C.WONO=B.WONO 
			    AND B.ITEM=A.ITEM`,
			self.Usr.Conn, new(common.RecDataStr), prtsn)
		ptyp := strings.TrimSpace(vals.(common.RecDataStr).Data)
		switch ptyp {
		case "A":
			urltype = "a"
		case "B":
			urltype = "p"
		case "C":
			urltype = "g"
		}
		if urltype == "a" {
			antennaPrint(self, self.Ctx, prtsn)
		}
		if urltype == "p" {
			passivePrint(self, self.Ctx, prtsn)
		}
		if urltype == "g" {
			gpsTestPrint(self, self.Ctx, prtsn)
		}
		return false
	}
	s_ssns := strings.TrimSpace(self.Ctx.Params["q"])
	if s_ssns != "" {
		self.Sqlparas = append(self.Sqlparas, s_ssns)
		self.SqlQueryExecute()
		return false
	} else {
		s_ssns = strings.TrimSpace(self.Ctx.Params["ssn"])
	}
	if s_ssns == "" {
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_ssns)

	return true
}

func (self *QuerySsnObj) SqlQueryExecute() {
	s_ssns := self.Sqlparas[0].(string)
	ssn_main := *common.FetchOneRowPtr(
		`SELECT TOP 1 T.SSN_NO,T.WONO,T.ITEM,T.CURR,ISNULL(C.BOXID,''),ISNULL(T.CUST_PRODNO,''),ISNULL(T.OLDSSN,''),ISNULL(D.SSN_NO,'')
           FROM
                (
                	SELECT A.SSN_NO, A.WONO, A.OLDSSN, A.CUST_PRODNO, B.ITEM, 
                			CASE WHEN A.ISSCRAPED=1 THEN 'SCRAP' WHEN A.ISFAILED=1 THEN 'REPAIR' ELSE A.CURR_STATION END AS CURR
                   	  FROM SFC_SSN A(NOLOCK), SFC_WO B(NOLOCK)
                     WHERE A.SSN_NO=?
                       AND A.WONO=B.WONO
                ) T
           LEFT JOIN SFC_BOXDETAIL C(NOLOCK) 
                 ON T.SSN_NO=C.SSN_NO
           LEFT JOIN SFC_PARTDETAIL D(NOLOCK)
				 ON T.SSN_NO=D.PARTID`,
		self.Usr.Conn, new(common.SsnMain), s_ssns)

	ssn_ls := *common.FetchAllRowsPtr(
		`SELECT A.SSN_NO, A.IDX, A.CURR_STATION, A.LINE, A.RESULT, ISNULL(B.NAME, A.MODIFYBY),
				 CONVERT(CHAR(23), A.MODIFYDATE, 121) 
           FROM SFC_SSNFLOW A(NOLOCK)
           LEFT JOIN ShopFloorControl.dbo.SFC_EMPLOYEE B(NOLOCK)
             ON A.MODIFYBY=B.ID
          WHERE A.SSN_NO=?
          ORDER BY A.IDX`,
		self.Usr.Conn, new(common.SsnStation), s_ssns)

	ssn_part := *common.FetchAllRowsPtr(
		`SELECT SSN_NO, ISNULL(PARTNAME, ''), ISNULL(PARTID,''), QTY 
           FROM SFC_PARTDETAIL(NOLOCK) 
          WHERE SSN_NO=? OR PARTID=?`,
		self.Usr.Conn, new(common.SsnParts), s_ssns, s_ssns)

	ssn_fail := *common.FetchAllRowsPtr(
		`SELECT SSN_NO, FAILSTATION,FAILCODE,ISNULL(FAILDESC,''),
                 ISNULL(REPAIRTYPE,''),ISNULL(REPAIRACTION,''),ISNULL(REPAIRDESC,'')
           FROM SFC_REPAIR(NOLOCK)
          WHERE SSN_NO=?`,
		self.Usr.Conn, new(common.SsnFailInfo), s_ssns)

	ssn_testinfo := *common.FetchAllRowsPtr(
		`SELECT A.SSN_NO, A.STATION, A.RESULT, A.MACHINEID, A.TOOLINGID,
				 A.TESTTIME, A.ESCAPETIME, A.TESTVERSION, ISNULL(B.NAME, A.MODIFYBY)
           FROM SFC_TESTSSN A(NOLOCK)
           LEFT JOIN ShopFloorControl.dbo.SFC_EMPLOYEE B(NOLOCK)
             ON A.MODIFYBY=B.ID
          WHERE A.SSN_NO=?`,
		self.Usr.Conn, new(common.SsnTestMain), s_ssns)

	ssn_testdetail := *common.FetchAllRowsPtr(
		`SELECT LTRIM(RTRIM(CONVERT(CHAR, TIMES))) + '-' + LTRIM(RTRIM(CONVERT(CHAR, IDX))),SSN_NO,STATION,TESTNAME,TESTTYPE,TESTDATA,
					TESTUNIT,LOWERLIMIT,UPPERLIMIT,RESULT,ISNULL(MODIFYBY, ''),CONVERT(CHAR(23), MODIFYDATE, 121) 
           FROM SFC_TESTDETAIL(NOLOCK) 
          WHERE SSN_NO=?`,
		self.Usr.Conn, new(common.SsnTestDetail), s_ssns)

	ssn_antenna := *common.FetchAllRowsPtr(
		`SELECT SSN_NO,LTRIM(RTRIM(CONVERT(CHAR, TIMES))) + '-' + LTRIM(RTRIM(CONVERT(CHAR, IDX))),
					TESTNAME,FREQUENCY,PORTS,SPECIFICATION,ISNULL(TESTDATA,''),ISNULL(RESULT,''),
					CONVERT(CHAR(23), MODIFYDATE, 121),MODIFYBY
		   FROM SFC_VSWRISOPP(NOLOCK) 
		  WHERE SSN_NO=?`,
		self.Usr.Conn, new(common.AntennaTest), s_ssns)

	self.TmplData["s_ssns"] = s_ssns
	self.TmplData["ssn_main"] = ssn_main
	self.TmplData["ssn_ls"] = ssn_ls
	self.TmplData["ssn_part"] = ssn_part
	self.TmplData["ssn_fail"] = ssn_fail
	self.TmplData["ssn_testinfo"] = ssn_testinfo
	self.TmplData["ssn_testdetail"] = ssn_testdetail
	self.TmplData["ssn_antenna"] = ssn_antenna
}

func QuerySSNHandler(ctx *web.Context) {
	self := new(QuerySsnObj)
	self.Ctx = ctx
	self.Html = "queryssn.html"
	self.Rightlist = []string{"queryssn"}
	self.DoQuery(self)
}

func getPassiveTestData(ssn, htmlFile, conn string) ([]*common.PassiveTestData, *common.PrintBaseData) {
	ssn = strings.ToUpper(ssn)
	ssn_testdetail := *common.FetchAllRowsPtr(
		`SELECT LTRIM(RTRIM(CONVERT(CHAR, TIMES))) + '-' + LTRIM(RTRIM(CONVERT(CHAR, IDX))),SSN_NO,STATION,TESTNAME,TESTTYPE,TESTDATA,
					TESTUNIT,LOWERLIMIT,UPPERLIMIT,RESULT,ISNULL(MODIFYBY, ''),CONVERT(CHAR(23), MODIFYDATE, 121)
           FROM SFC_TESTDETAIL(NOLOCK)
          WHERE SSN_NO=?
          ORDER BY MODIFYDATE`,
		conn, new(common.SsnTestDetail), ssn)
	printset := *common.FetchAllRowsPtr(
		`SELECT A.ITEM,A.PARAMETER,A.TESTNAME,A.FREQUENCY,A.PORT,A.SPECIFICATION
           FROM SFC_ITEMSTEST A(NOLOCK), SFC_WO B(NOLOCK), SFC_SSN C(NOLOCK)           
          WHERE C.SSN_NO=?
            AND C.WONO=B.WONO
            AND B.ITEM=A.ITEM
          ORDER BY A.IDX`,
		conn, new(common.PassiveFrequency), ssn)
	ssn_vswriso := *common.FetchAllRowsPtr(
		`SELECT IDX,SSN_NO,STATION,TESTNAME,'',TESTDATA,'','','',
					RESULT,ISNULL(MODIFYBY, ''),CONVERT(CHAR(23), MODIFYDATE, 121)
           FROM SFC_VSWRISOPP(NOLOCK)
          WHERE SSN_NO=?
          ORDER BY MODIFYDATE`,
		conn, new(common.SsnTestDetail), ssn)
	basedata := new(common.PrintBaseData)
	var datalist []*common.PassiveTestData
	for _, val := range printset {
		value := new(common.PassiveTestData)
		value.Item = strings.TrimSpace(val.(common.PassiveFrequency).Item)
		value.Parameter = strings.TrimSpace(val.(common.PassiveFrequency).Parameter)
		value.TestName = strings.TrimSpace(val.(common.PassiveFrequency).TestName)
		value.Frequency = strings.TrimSpace(val.(common.PassiveFrequency).Frequency)
		value.Specification = strings.TrimSpace(val.(common.PassiveFrequency).Specification)
		value.Ports = strings.TrimSpace(val.(common.PassiveFrequency).Ports)
		datalist = append(datalist, value)
	}
	multDict := make(map[string][]string)
	for _, val := range ssn_testdetail {
		testname := strings.TrimSpace(val.(common.SsnTestDetail).TestName)
		testdata := strings.TrimSpace(val.(common.SsnTestDetail).TestData)
		result := strings.TrimSpace(val.(common.SsnTestDetail).Result)
		basedata.Operator = strings.TrimSpace(val.(common.SsnTestDetail).Operator)
		c_date, _ := time.Parse("2006-01-02 15:04:05", strings.TrimSpace(val.(common.SsnTestDetail).Date))
		basedata.Date = c_date.Format("01-02-2006")
		for _, v := range datalist {
			s_names := strings.Split(v.TestName, ",")
			if len(s_names) == 1 {
				if v.TestName != testname {
					continue
				}
				v.Data = testdata
				v.Result = result
			}
			if len(s_names) == 2 {
				if _, ok := multDict[v.TestName]; !ok {
					multDict[v.TestName] = []string{"", "PASS", "", "PASS"}
				}
				name01 := strings.TrimSpace(s_names[0])
				name02 := strings.TrimSpace(s_names[1])
				if name01 == testname {
					multDict[v.TestName][0] = testdata
					multDict[v.TestName][1] = result
				}
				if name02 == testname {
					multDict[v.TestName][2] = testdata
					multDict[v.TestName][3] = result
				}
			}
		}
	}
	for _, v := range datalist {
		if val, ok := multDict[v.TestName]; ok {
			v.Data = val[0] + " - " + val[2]
			v.Result = "PASS"
			if val[1] == "FAIL" {
				v.Result = "FAIL"
			}
			if val[3] == "FAIL" {
				v.Result = "FAIL"
			}
			delete(multDict, v.TestName)
		}
	}
	for _, val := range ssn_vswriso {
		testname := strings.TrimSpace(val.(common.SsnTestDetail).TestName)
		result := strings.TrimSpace(val.(common.SsnTestDetail).Result)
		for _, v := range datalist {
			if v.TestName != testname {
				continue
			}
			if result == "PASS" {
				v.Data = "OK"
				v.Result = "PASS"
			} else {
				v.Data = ""
				v.Result = "FAIL"
			}
		}
	}

	vers := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(A.VERS, '') 
		   FROM SFC_PRINTVERSION A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
		  WHERE B.SSN_NO=?
		    AND B.WONO=C.WONO 
		    AND C.ITEM=A.ITEM`,
		conn, new(common.RecDataStr), ssn)
	basedata.Version = strings.TrimSpace(vers.(common.RecDataStr).Data)
	if basedata.Version == "" {
		basedata.Version = "NT-TR-S-001_V1.0"
	}
	model := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(A.RPTDESC, '') 
		   FROM SFC_ITEMRPT A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
		  WHERE B.SSN_NO=?
		    AND B.WONO=C.WONO 
		    AND C.ITEM=A.ITEM`,
		conn, new(common.RecDataStr), ssn)
	basedata.Model = strings.TrimSpace(model.(common.RecDataStr).Data)

	basedata.Serial = ssn
	qcinfo := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(MODIFYBY, ''), CONVERT(CHAR(23), MODIFYDATE, 121) 
		   FROM SFC_SSNFLOW(NOLOCK) 
		  WHERE SSN_NO=? 
		    AND CURR_STATION='WO INSPECTION-FINAL' 
		  ORDER BY MODIFYDATE DESC`,
		conn, new(common.QcInfo), ssn)
	basedata.QcOper = strings.TrimSpace(qcinfo.(common.QcInfo).QcOper)
	c_date, _ := time.Parse("2006-01-02 15:04:05", strings.TrimSpace(qcinfo.(common.QcInfo).QcDate))
	basedata.QcDate = c_date.Format("01-02-2006")

	failFlg := false
	for _, v := range datalist {
		if v.Result == "FAIL" {
			failFlg = true
			break
		}
	}
	if failFlg {
		datalist = []*common.PassiveTestData{}
	}

	return datalist, basedata
}

func GetAntennaTestData(ssn, conn string) (*common.AntennaDataPrint, []*common.AntennaRptStruct, []*common.AntennaRptStruct) {
	ssn = strings.ToUpper(ssn)
	ssn_VSWR := *common.FetchAllRowsPtr(
		`SELECT TESTNAME,FREQUENCY,SPECIFICATION,[PORTS],ISNULL(TESTDATA,''),ISNULL(RESULT,'')
		   FROM (
		   		 SELECT *, RN=ROW_NUMBER() OVER(PARTITION BY FREQUENCY, [PORTS] ORDER BY MODIFYDATE DESC) 
		   		   FROM SFC_VSWRISOPP(NOLOCK) 
		   		  WHERE SSN_NO=? AND TESTNAME='VSWR') K 
		  WHERE K.RN=1
		  ORDER BY [PORTS]`,
		conn, new(common.AntennaRptStruct), ssn)
	if len(ssn_VSWR) == 0 {
		ssn_VSWR = *common.FetchAllRowsPtr(
			`SELECT TESTNAME,FREQUENCY,SPECIFICATION,[PORTS],ISNULL(TESTDATA,''),ISNULL(RESULT,'')
			   FROM (
			   		 SELECT *, RN=ROW_NUMBER() OVER(PARTITION BY FREQUENCY, [PORTS] ORDER BY MODIFYDATE DESC) 
			   		   FROM SFC_VSWRISOPP(NOLOCK) 
			   		  WHERE SSN_NO=? AND TESTNAME='Pre VSWR') K 
			  WHERE K.RN=1
			  ORDER BY [PORTS]`,
			conn, new(common.AntennaRptStruct), ssn)
	}
	ssn_Iso := *common.FetchAllRowsPtr(
		`SELECT TESTNAME,FREQUENCY,SPECIFICATION,[PORTS],ISNULL(TESTDATA,''),ISNULL(RESULT,'')
		   FROM (
		   		 SELECT *, RN=ROW_NUMBER() OVER(PARTITION BY [PORTS] ORDER BY MODIFYDATE DESC) 
		   		   FROM SFC_VSWRISOPP(NOLOCK) 
		   		  WHERE SSN_NO=? AND TESTNAME='Isolation(dB)') K 
		  WHERE K.RN=1
		  ORDER BY [PORTS]`,
		conn, new(common.AntennaRptStruct), ssn)
	if len(ssn_Iso) == 0 {
		ssn_Iso = *common.FetchAllRowsPtr(
			`SELECT TESTNAME,FREQUENCY,SPECIFICATION,[PORTS],ISNULL(TESTDATA,''),ISNULL(RESULT,'')
			   FROM (
			   		 SELECT *, RN=ROW_NUMBER() OVER(PARTITION BY [PORTS] ORDER BY MODIFYDATE DESC) 
			   		   FROM SFC_VSWRISOPP(NOLOCK) 
			   		  WHERE SSN_NO=? AND TESTNAME='Pre Isolation(dB)') K 
			  WHERE K.RN=1
			  ORDER BY [PORTS]`,
			conn, new(common.AntennaRptStruct), ssn)
	}
	ssn_Imd := *common.FetchAllRowsPtr(
		`SELECT TESTNAME,FREQUENCY,SPECIFICATION,[PORTS],ISNULL(TESTDATA,''),ISNULL(RESULT,'')
		   FROM (
		   		 SELECT *, RN=ROW_NUMBER() OVER(PARTITION BY FREQUENCY, [PORTS] ORDER BY MODIFYDATE DESC) 
		   		   FROM SFC_VSWRISOPP(NOLOCK) 
		   		  WHERE SSN_NO=? AND TESTNAME='IMD(3rd)(dBm)') K 
		  WHERE K.RN=1
		  ORDER BY [PORTS]`,
		conn, new(common.AntennaRptStruct), ssn)
	ssn_BeamPeak := *common.FetchAllRowsPtr(
		`SELECT TESTNAME,FREQUENCY,SPECIFICATION,[PORTS],ISNULL(TESTDATA,''),ISNULL(RESULT,'')
		   FROM (
		   		 SELECT *, RN=ROW_NUMBER() OVER(PARTITION BY [PORTS] ORDER BY MODIFYDATE DESC) 
		   		   FROM SFC_VSWRISOPP(NOLOCK) 
		   		  WHERE SSN_NO=? AND TESTNAME='Beam Peak') K 
		  WHERE K.RN=1
		  ORDER BY [PORTS]`,
		conn, new(common.AntennaRptStruct), ssn)
	ssn_BeamWidth := *common.FetchAllRowsPtr(
		`SELECT TESTNAME,FREQUENCY,SPECIFICATION,[PORTS],ISNULL(TESTDATA,''),ISNULL(RESULT,'')
		   FROM (
		   		 SELECT *, RN=ROW_NUMBER() OVER(PARTITION BY [PORTS] ORDER BY MODIFYDATE DESC) 
		   		   FROM SFC_VSWRISOPP(NOLOCK) 
		   		  WHERE SSN_NO=? AND TESTNAME='Beam Width') K 
		  WHERE K.RN=1
		  ORDER BY [PORTS]`,
		conn, new(common.AntennaRptStruct), ssn)
	ssn_testdate := *common.FetchOneRowPtr(
		`SELECT TOP 1 CONVERT(CHAR(23), MODIFYDATE, 121),ISNULL(MODIFYBY, 'SysAuto')
		   FROM SFC_VSWRISOPP(NOLOCK)
		  WHERE SSN_NO=?
		  ORDER BY MODIFYDATE DESC`,
		conn, new(common.NormalStruct), ssn)
	values := new(common.AntennaDataPrint)
	values.Result = "PASS"
	values.Serial = ssn
	c_date, _ := time.Parse("2006-01-02 15:04:05", strings.TrimSpace(ssn_testdate.(common.NormalStruct).Value1))
	values.Date = c_date.Format("01-02-2006")
	values.Operator = strings.TrimSpace(ssn_testdate.(common.NormalStruct).Value2)
	values.ElecB = false
	values.PhaseB = false

	item := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(A.ITEM, '') 
		   FROM SFC_WO A(NOLOCK), SFC_SSN B(NOLOCK)
		  WHERE B.SSN_NO=?
		    AND B.WONO=A.WONO`,
		conn, new(common.RecDataStr), ssn)
	values.Item = strings.TrimSpace(item.(common.RecDataStr).Data)

	ssn_spec := *common.FetchAllRowsPtr(
		`SELECT PARAMETER, PORTNUM, SPECIFICATION 
		   FROM SFC_REPORTSPEC(NOLOCK) 
		  WHERE item=?`,
		conn, new(common.ReportSpec), values.Item)

	var elec_totals []*common.AntennaRptStruct
	var phase_totals []*common.AntennaRptStruct

	for _, val := range ssn_VSWR {
		parameter := strings.TrimSpace(val.(common.AntennaRptStruct).Parameter)
		if parameter == "Pre VSWR" {
			parameter = "VSWR"
		}

		freq := strings.TrimSpace(val.(common.AntennaRptStruct).Frequency)
		freq = strings.TrimSpace(strings.Replace(freq, "MHz", "", -1))
		freq = strings.Replace(freq, "-", "~", -1)
		freq = strings.Replace(freq, ",", "~", -1)

		spec := strings.TrimSpace(val.(common.AntennaRptStruct).Specification)

		port := strings.TrimSpace(val.(common.AntennaRptStruct).Ports)

		data_f, _ := strconv.ParseFloat(strings.TrimSpace(val.(common.AntennaRptStruct).Data), 64)
		data := strings.TrimSpace(strconv.FormatFloat(data_f, 'f', 2, 32))

		result := strings.TrimSpace(val.(common.AntennaRptStruct).Result)
		if result == "FAIL" {
			values.Result = "FAIL"
		}

		values.ElecB = true

		for _, v := range ssn_spec {
			spec_name := strings.TrimSpace(v.(common.ReportSpec).Parameter)
			ports := strings.TrimSpace(v.(common.ReportSpec).Ports)
			spec_value := strings.TrimSpace(v.(common.ReportSpec).Specification)
			if spec_name == parameter && ports == port {
				spec = spec_value
			}
		}

		curr := new(common.AntennaRptStruct)
		curr.Parameter = parameter
		curr.Frequency = freq
		curr.Specification = spec
		curr.Ports = port
		curr.Data = data
		curr.Result = result

		elec_totals = append(elec_totals, curr)
	}
	for _, val := range ssn_Iso {
		parameter := strings.TrimSpace(val.(common.AntennaRptStruct).Parameter)
		if parameter == "Pre Isolation(dB)" {
			parameter = "Isolation(dB)"
		}

		freq := strings.TrimSpace(val.(common.AntennaRptStruct).Frequency)
		freq = strings.TrimSpace(strings.Replace(freq, "MHz", "", -1))
		freq = strings.Replace(freq, "-", "~", -1)
		freq = strings.Replace(freq, ",", "~", -1)

		spec := strings.TrimSpace(val.(common.AntennaRptStruct).Specification)

		port := strings.TrimSpace(val.(common.AntennaRptStruct).Ports)

		data_f, _ := strconv.ParseFloat(strings.TrimSpace(val.(common.AntennaRptStruct).Data), 64)
		data := strings.TrimSpace(strconv.FormatFloat(data_f, 'f', 2, 32))

		result := strings.TrimSpace(val.(common.AntennaRptStruct).Result)
		if result == "FAIL" {
			values.Result = "FAIL"
		}

		values.ElecB = true

		for _, v := range ssn_spec {
			spec_name := strings.TrimSpace(v.(common.ReportSpec).Parameter)
			ports := strings.TrimSpace(v.(common.ReportSpec).Ports)
			spec_value := strings.TrimSpace(v.(common.ReportSpec).Specification)
			if spec_name == parameter && ports == port {
				spec = spec_value
			}
		}

		curr := new(common.AntennaRptStruct)
		curr.Parameter = parameter
		curr.Frequency = freq
		curr.Specification = spec
		curr.Ports = port
		curr.Data = data
		curr.Result = result

		elec_totals = append(elec_totals, curr)
	}
	for _, val := range ssn_Imd {
		parameter := strings.TrimSpace(val.(common.AntennaRptStruct).Parameter)

		freq := strings.TrimSpace(val.(common.AntennaRptStruct).Frequency)
		freq = strings.TrimSpace(strings.Replace(freq, "MHz", "", -1))
		freq = strings.Replace(freq, "-", "~", -1)
		freq = strings.Replace(freq, ",", "~", -1)

		spec := strings.TrimSpace(val.(common.AntennaRptStruct).Specification)

		port := strings.TrimSpace(val.(common.AntennaRptStruct).Ports)

		data_f, _ := strconv.ParseFloat(strings.TrimSpace(val.(common.AntennaRptStruct).Data), 64)
		data := strings.TrimSpace(strconv.FormatFloat(data_f, 'f', 2, 32))

		result := strings.TrimSpace(val.(common.AntennaRptStruct).Result)
		if result == "FAIL" {
			values.Result = "FAIL"
		}

		values.ElecB = true

		for _, v := range ssn_spec {
			spec_name := strings.TrimSpace(v.(common.ReportSpec).Parameter)
			ports := strings.TrimSpace(v.(common.ReportSpec).Ports)
			spec_value := strings.TrimSpace(v.(common.ReportSpec).Specification)
			if spec_name == parameter && ports == port {
				spec = spec_value
			}
		}

		curr := new(common.AntennaRptStruct)
		curr.Parameter = parameter
		curr.Frequency = freq
		curr.Specification = spec
		curr.Ports = port
		curr.Data = data
		curr.Result = result

		elec_totals = append(elec_totals, curr)
	}
	for _, val := range ssn_BeamPeak {
		parameter := strings.TrimSpace(val.(common.AntennaRptStruct).Parameter)

		spec := strings.TrimSpace(val.(common.AntennaRptStruct).Specification)

		port := strings.TrimSpace(val.(common.AntennaRptStruct).Ports)

		data_f, _ := strconv.ParseFloat(strings.TrimSpace(val.(common.AntennaRptStruct).Data), 64)
		data := strings.TrimSpace(strconv.FormatFloat(data_f, 'f', 2, 32))

		result := strings.TrimSpace(val.(common.AntennaRptStruct).Result)
		if result == "FAIL" {
			values.Result = "FAIL"
		}

		values.PhaseB = true

		for _, v := range ssn_spec {
			spec_name := strings.TrimSpace(v.(common.ReportSpec).Parameter)
			ports := strings.TrimSpace(v.(common.ReportSpec).Ports)
			spec_value := strings.TrimSpace(v.(common.ReportSpec).Specification)
			if spec_name == parameter && ports == port {
				spec = spec_value
			}
		}

		curr := new(common.AntennaRptStruct)
		curr.Parameter = parameter
		curr.Specification = spec
		curr.Ports = port
		curr.Data = data
		curr.Result = result

		phase_totals = append(phase_totals, curr)
	}
	for _, val := range ssn_BeamWidth {
		parameter := strings.TrimSpace(val.(common.AntennaRptStruct).Parameter)

		spec := strings.TrimSpace(val.(common.AntennaRptStruct).Specification)

		port := strings.TrimSpace(val.(common.AntennaRptStruct).Ports)

		data_f, _ := strconv.ParseFloat(strings.TrimSpace(val.(common.AntennaRptStruct).Data), 64)
		data := strings.TrimSpace(strconv.FormatFloat(data_f, 'f', 2, 32))

		result := strings.TrimSpace(val.(common.AntennaRptStruct).Result)
		if result == "FAIL" {
			values.Result = "FAIL"
		}

		values.PhaseB = true

		for _, v := range ssn_spec {
			spec_name := strings.TrimSpace(v.(common.ReportSpec).Parameter)
			ports := strings.TrimSpace(v.(common.ReportSpec).Ports)
			spec_value := strings.TrimSpace(v.(common.ReportSpec).Specification)
			if spec_name == parameter && ports == port {
				spec = spec_value
			}
		}

		curr := new(common.AntennaRptStruct)
		curr.Parameter = parameter
		curr.Specification = spec
		curr.Ports = port
		curr.Data = data
		curr.Result = result

		phase_totals = append(phase_totals, curr)
	}

	if values.Result != "FAIL" {
		vers := *common.FetchOneRowPtr(
			`SELECT TOP 1 ISNULL(A.VERS, '') 
			   FROM SFC_PRINTVERSION A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
			  WHERE B.SSN_NO=?
			    AND B.WONO=C.WONO 
			    AND C.ITEM=A.ITEM`,
			conn, new(common.RecDataStr), ssn)
		values.Version = strings.TrimSpace(vers.(common.RecDataStr).Data)
		if values.Version == "" {
			values.Version = "NT-TR-S-001_V1.0"
		}
		model := *common.FetchOneRowPtr(
			`SELECT TOP 1 ISNULL(A.DESCRIP, '') 
			   FROM SFC_ITEMS A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
			  WHERE B.SSN_NO=?
			    AND B.WONO=C.WONO 
			    AND C.ITEM=A.ITEM`,
			conn, new(common.RecDataStr), ssn)
		values.Model = strings.TrimSpace(model.(common.RecDataStr).Data)
	} else {
		values.ElecB = false
		values.PhaseB = false
	}

	return values, elec_totals, phase_totals
}

func getGpsTestData(ssn, htmlFile, conn string) ([]*common.GpsTestingData, *common.PrintBaseData) {
	ssn = strings.ToUpper(ssn)
	ssn_testdetail := *common.FetchAllRowsPtr(
		`SELECT LTRIM(RTRIM(CONVERT(CHAR, TIMES))) + '-' + LTRIM(RTRIM(CONVERT(CHAR, IDX))),SSN_NO,STATION,TESTNAME,TESTTYPE,TESTDATA,
					TESTUNIT,LOWERLIMIT,UPPERLIMIT,RESULT,ISNULL(MODIFYBY, ''),CONVERT(CHAR(23), MODIFYDATE, 121)
           FROM SFC_TESTDETAIL(NOLOCK)
          WHERE SSN_NO=?
          ORDER BY MODIFYDATE`,
		conn, new(common.SsnTestDetail), ssn)
	printset := *common.FetchAllRowsPtr(
		`SELECT A.ITEM,A.PARAMETER,A.TESTNAME,A.FREQUENCY,A.SPECIFICATION
           FROM SFC_ITEMSTEST A(NOLOCK), SFC_WO B(NOLOCK), SFC_SSN C(NOLOCK)           
          WHERE C.SSN_NO=?
            AND C.WONO=B.WONO
            AND B.ITEM=A.ITEM
          ORDER BY A.IDX`,
		conn, new(common.GpsFrequency), ssn)
	ssn_vswriso := *common.FetchAllRowsPtr(
		`SELECT IDX,SSN_NO,STATION,TESTNAME,'',TESTDATA,'','','',
					RESULT,ISNULL(MODIFYBY, ''),CONVERT(CHAR(23), MODIFYDATE, 121)
           FROM SFC_VSWRISOPP(NOLOCK)
          WHERE SSN_NO=?
          ORDER BY MODIFYDATE`,
		conn, new(common.SsnTestDetail), ssn)
	basedata := new(common.PrintBaseData)
	var datalist []*common.GpsTestingData
	for _, val := range printset {
		value := new(common.GpsTestingData)
		value.Item = strings.TrimSpace(val.(common.GpsFrequency).Item)
		value.Parameter = strings.TrimSpace(val.(common.GpsFrequency).Parameter)
		value.TestName = strings.TrimSpace(val.(common.GpsFrequency).TestName)
		value.Frequency = strings.TrimSpace(val.(common.GpsFrequency).Frequency)
		value.Specification = strings.TrimSpace(val.(common.GpsFrequency).Specification)
		datalist = append(datalist, value)
	}
	multDict := make(map[string][]string)
	for _, val := range ssn_testdetail {
		testname := strings.TrimSpace(val.(common.SsnTestDetail).TestName)
		testdata := strings.TrimSpace(val.(common.SsnTestDetail).TestData)
		result := strings.TrimSpace(val.(common.SsnTestDetail).Result)
		basedata.Operator = strings.TrimSpace(val.(common.SsnTestDetail).Operator)
		c_date, _ := time.Parse("2006-01-02 15:04:05", strings.TrimSpace(val.(common.SsnTestDetail).Date))
		basedata.Date = c_date.Format("01-02-2006")
		for _, v := range datalist {
			s_names := strings.Split(v.TestName, ",")
			if len(s_names) == 1 {
				if v.TestName != testname {
					continue
				}
				v.Data = testdata
				v.Result = result
			}
			if len(s_names) == 2 {
				if _, ok := multDict[v.TestName]; !ok {
					multDict[v.TestName] = []string{"", "PASS", "", "PASS"}
				}
				name01 := strings.TrimSpace(s_names[0])
				name02 := strings.TrimSpace(s_names[1])
				if name01 == testname {
					multDict[v.TestName][0] = testdata
					multDict[v.TestName][1] = result
				}
				if name02 == testname {
					multDict[v.TestName][2] = testdata
					multDict[v.TestName][3] = result
				}
			}
		}
	}
	for _, v := range datalist {
		if val, ok := multDict[v.TestName]; ok {
			v.Data = val[0] + " - " + val[2]
			v.Result = "PASS"
			if val[1] == "FAIL" {
				v.Result = "FAIL"
			}
			if val[3] == "FAIL" {
				v.Result = "FAIL"
			}
			delete(multDict, v.TestName)
		}
	}
	for _, val := range ssn_vswriso {
		testname := strings.TrimSpace(val.(common.SsnTestDetail).TestName)
		result := strings.TrimSpace(val.(common.SsnTestDetail).Result)
		for _, v := range datalist {
			if v.TestName != testname {
				continue
			}
			if result == "PASS" {
				v.Data = "OK"
				v.Result = "PASS"
			} else {
				v.Data = ""
				v.Result = "FAIL"
			}
		}
	}

	vers := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(A.VERS, '') 
		   FROM SFC_PRINTVERSION A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
		  WHERE B.SSN_NO=?
		    AND B.WONO=C.WONO 
		    AND C.ITEM=A.ITEM`,
		conn, new(common.RecDataStr), ssn)
	basedata.Version = strings.TrimSpace(vers.(common.RecDataStr).Data)
	if basedata.Version == "" {
		basedata.Version = "NT-TR-S-001_V1.0"
	}
	model := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(A.RPTDESC, '') 
		   FROM SFC_ITEMRPT A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
		  WHERE B.SSN_NO=?
		    AND B.WONO=C.WONO 
		    AND C.ITEM=A.ITEM`,
		conn, new(common.RecDataStr), ssn)
	basedata.Model = strings.TrimSpace(model.(common.RecDataStr).Data)

	basedata.Serial = ssn
	qcinfo := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(MODIFYBY, ''), CONVERT(CHAR(23), MODIFYDATE, 121) 
		   FROM SFC_SSNFLOW(NOLOCK) 
		  WHERE SSN_NO=? 
		    AND CURR_STATION='WO INSPECTION-FINAL' 
		  ORDER BY MODIFYDATE DESC`,
		conn, new(common.QcInfo), ssn)
	basedata.QcOper = strings.TrimSpace(qcinfo.(common.QcInfo).QcOper)
	c_date, _ := time.Parse("2006-01-02 15:04:05", strings.TrimSpace(qcinfo.(common.QcInfo).QcDate))
	basedata.QcDate = c_date.Format("01-02-2006")

	failFlg := false
	for _, v := range datalist {
		if v.Result == "FAIL" {
			failFlg = true
			break
		}
	}
	if failFlg {
		datalist = []*common.GpsTestingData{}
	}

	return datalist, basedata
}

func passivePrint(self *QuerySsnObj, ctx *web.Context, ssn string) {
	pntset := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(A.SQLTEXT, ''), ISNULL(A.HTMLFILE, '')
		   FROM SFC_PRINTVERSION A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
		  WHERE B.SSN_NO=?
		    AND B.WONO=C.WONO 
		    AND C.ITEM=A.ITEM`,
		self.Usr.Conn, new(common.PrintSqlAndFile), ssn)
	htmlFile := strings.TrimSpace(pntset.(common.PrintSqlAndFile).Htmlfile)
	if htmlFile == "" {
		htmlFile = "EIMFI_IMComb.html"
	}
	datalist, basedata := getPassiveTestData(ssn, htmlFile, self.Usr.Conn)
	self.TmplData["values"] = datalist
	self.TmplData["basedata"] = basedata
	self.Single = htmlFile
	self.Html = ""
}

func antennaPrint(self *QuerySsnObj, ctx *web.Context, ssn string) {
	vals, elec, phase := GetAntennaTestData(ssn, self.Usr.Conn)
	self.TmplData["values"] = vals
	self.TmplData["elecs"] = elec
	self.TmplData["phases"] = phase
	self.Single = "antennaPrint.html"
	self.Html = ""
}

func gpsTestPrint(self *QuerySsnObj, ctx *web.Context, ssn string) {
	pntset := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(A.SQLTEXT, ''), ISNULL(A.HTMLFILE, '')
		   FROM SFC_PRINTVERSION A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
		  WHERE B.SSN_NO=?
		    AND B.WONO=C.WONO 
		    AND C.ITEM=A.ITEM`,
		self.Usr.Conn, new(common.PrintSqlAndFile), ssn)
	htmlFile := strings.TrimSpace(pntset.(common.PrintSqlAndFile).Htmlfile)
	if htmlFile == "" {
		htmlFile = "GPSTestPrint.html"
	}
	datalist, basedata := getGpsTestData(ssn, htmlFile, self.Usr.Conn)
	self.TmplData["values"] = datalist
	self.TmplData["basedata"] = basedata
	self.Single = htmlFile
	self.Html = ""
}
